package com.Jhu1.service.impl;

import cn.hutool.core.util.StrUtil;
import com.Jhu1.entity.Class;
import com.Jhu1.entity.Student;
import com.Jhu1.mapper.StudentMapper;
import com.Jhu1.service.IClassService;
import com.Jhu1.service.IStudentService;
import com.Jhu1.util.PageResult;
import com.Jhu1.vo.StudentVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zjh
 * @since 2025-01-07
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Autowired
    private IClassService classesService;

    @Override
    public PageResult<Student> findByPage(Integer page, Integer pageSize) {
        // 获取分页数据
        Page<Student> page_first = this.page(new Page<>(page, pageSize));

        // 返回分页结果
        return new PageResult<>(page_first.getRecords(), page_first.getTotal());
    }

    @Override
    public PageResult<Student> searchStudent(Integer page, Integer pageSize, StudentVO vo) {
        QueryWrapper<Student> wrapper = new QueryWrapper<>();
        // 根据条件构建查询
        wrapper.like(StrUtil.isNotBlank(vo.getSname()), "sname", vo.getSname());
        wrapper.like(StrUtil.isNotBlank(vo.getSex()), "sex", vo.getSex());
        wrapper.like(StrUtil.isNotBlank(vo.getAddr()), "address", vo.getAddr());
        wrapper.eq( vo.getCid() != 0, "cid", vo.getCid());
        Page<Student> page1 = this.page(new Page<>(page, pageSize), wrapper);
        page1.getRecords().forEach(st -> {
            if (st.getCid() != null) {
                Class classes = classesService.getById(st.getCid());
                if (classes != null) {
                    st.setCname(classes.getCname());  // 设置班级名称
                }
            }
        });
        return new PageResult<>(page1.getRecords(), page1.getTotal());
    }

}
